<template>
  <div class="category-manage">
    <div class="header">
      <el-button type="primary" @click="showAddDialog">添加分类</el-button>
    </div>

    <el-table
      :data="categoryList"
      row-key="id"
      border
      default-expand-all
      :tree-props="{children: 'children'}">
      <el-table-column prop="name" label="分类名称"></el-table-column>
      <el-table-column prop="sort" label="层级" width="100">
        <template slot-scope="scope">
          {{ scope.row.sort === 1 ? '一级分类' : '二级分类' }}
        </template>
      </el-table-column>
      <el-table-column prop="sort" label="排序" width="100"></el-table-column>
      <el-table-column label="状态" width="100">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(scope.row)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template slot-scope="scope">
          <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="text" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible">
      <el-form :model="categoryForm" :rules="rules" ref="categoryForm" label-width="100px">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="categoryForm.name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类" prop="parentId">
          <el-select v-model="categoryForm.parentId" placeholder="请选择">
            <el-option label="无(一级分类)" :value="0"></el-option>
            <el-option
              v-for="item in parentCategories"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="categoryForm.sort" :min="0"></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getCategoryList, saveCategory, deleteCategory, updateCategoryStatus } from '@/api/category.js'

export default {
  name: 'CategoryManage',
  data() {
    return {
      categoryList: [],
      parentCategories: [],
      dialogVisible: false,
      dialogTitle: '添加分类',
      categoryForm: {
        name: '',
        parentId: 0,
        sort: 0
      },
      rules: {
        name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    async getList() {
      try {
        const { data } = await getCategoryList()
        console.log('data', data)
        this.categoryList = this.formatCategoryTree(data)
        console.log('132321', this.categoryList)
        this.parentCategories = data.filter(item => item.sort === 1)
      } catch (error) {
        this.$message.error('获取分类列表失败')
      }
    },
    formatCategoryTree(list) {
      const parents = list.filter(item => item.sort === 1)
      parents.forEach(parent => {
        parent.children = list.filter(item => item.parentId === parent.id)
      })
      return parents
    },
    showAddDialog() {
      this.dialogTitle = '添加分类'
      this.categoryForm = {
        name: '',
        parentId: 0,
        sort: 0 
      }
      this.dialogVisible = true
    },
    handleEdit(row) {
      this.dialogTitle = '编辑分类'
      this.categoryForm = { ...row }
      this.dialogVisible = true
    },
    async handleSubmit() {
      this.$refs.categoryForm.validate(async valid => {
        if (valid) {
          try {
            await saveCategory(this.categoryForm)
            this.$message.success('保存成功')
            this.dialogVisible = false
            this.getList()
          } catch (error) {
            this.$message.error('保存失败')
          }
        }
      })
    },
    async handleDelete(row) {
      if (row.children && row.children.length > 0) {
        return this.$message.warning('请先删除子分类')
      }
      try {
        await this.$confirm('确认删除该分类?', '提示', {
          type: 'warning'
        })
        await deleteCategory(row.id)
        this.$message.success('删除成功')
        this.getList()
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败')
        }
      }
    },
    async handleStatusChange(row) {
      try {
        await updateCategoryStatus({
          id: row.id,
          status: row.status
        })
        this.$message.success('状态更新成功')
      } catch (error) {
        this.$message.error('状态更新失败')
        row.status = row.status === 1 ? 0 : 1
      }
    }
  }
}
</script>

<style scoped>
.category-manage {
  padding: 20px;
}
.header {
  margin-bottom: 20px;
}
</style> 